package com.kason.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 基于角色的登陆入口控制器
 * Created by IBM on 2018/6/30.
 */
public class LoginUrlEntryPoint extends LoginUrlAuthenticationEntryPoint {


    private final Map<String, String> authEntryPointMap;
    private PathMatcher pathMatcher = new AntPathMatcher(); // 用于进行url 模式匹配用。
    public LoginUrlEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
        authEntryPointMap = new HashMap<>();
        // 普通用户登录入口映射， url模式匹配
        authEntryPointMap.put("/user/**", "/user/login");
        // 管理员登录入口映射， url模式匹配
        authEntryPointMap.put("/admin/**", "/admin/login");
    }

    /**
     * 根据请求跳转到指定的页面， 父类是默认使用的loginFormUrl
     * @param request
     * @param response
     * @param exception
     * @return
     */
    @Override
    protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        // 首先获取要跳转的url是什么
        String replace = request.getRequestURI().replace(request.getContextPath(), ""); //本地就是去除http://localhost:8081替换成""
        // 比如http://localhost:8081/admin/center 将调到http://localhost:8081/admin/login
        // http://localhost:8081/user/center 将会跳转到http://localhost:8081/user/login
        for(Map.Entry<String, String> entry : this.authEntryPointMap.entrySet()) {

            if (this.pathMatcher.match(entry.getKey(), replace)) {
                return entry.getValue();
            }

        }
        return super.determineUrlToUseForThisRequest(request, response, exception);
    }
}
